#! c:\Python27\python.exe

from MySocket import MySocket
import socket
import Tkinter
import tkMessageBox
import tkSimpleDialog
import thread
import threading
from Tkinter import *

from config import config

class NetworkManager(tkSimpleDialog.Dialog):
    def body(self, master):
		Label(master, text="Address").grid(row=0, sticky=W)
		Label(master, text="Port").grid(row=1, sticky=W)

		self.e1 = Entry(master)
		self.e1.insert(0, "127.0.0.1")
		self.e2 = Entry(master)
		self.e2.insert(0, config["ChatServerPort"])

		self.e1.grid(row=0, column=1)
		self.e2.grid(row=1, column=1)
		return self.e1 # initial focus

    def apply(self):
		address = self.e1.get()
		port = self.e2.get()
		
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((address, int(port)))
		self.conn = s

class ChatRoomClient(PanedWindow):
	def __init__(self, master=None):
		PanedWindow.__init__(self, master, orient=VERTICAL)
		self.pack(fill=BOTH, expand=1)
		self.createWidgets()
		
		self.TEXT.insert(0, repr(config))
		networkmanager = NetworkManager(self)
		self.conn = networkmanager.conn
		ack = MySocket.recvObject(self.conn)
		assert(ack[0] == 'clientID')
		self.my_id = ack[1]
		print 'my_id = %s' % self.my_id
		thread.start_new_thread(self.serverMessageHandler, () )
		
	def serverMessageHandler(self):
		while True:
			try:
				data = MySocket.recvObject(self.conn)
				print data
				if (len(data) < 1):
					continue
				cmd = data[0]
				if (cmd == 'message'):
					id = "anonymity"
					message = ""
					
					if (len(data) > 1):
						message = data[1]
					if (len(data) > 2):
						id = data[2]
					
					if (id != self.my_id):
						self.appendMessage("%s: %s" % (id, message) )
					continue
				
				print 'warning: empty package received from server'
					
			except Exception as inst:
				print 'serverMessageHandler thread exits'
				print type(inst)
				print inst.args
				
	def appendMessage(self, message):
		self.TEXT.insert(self.TEXT.size() + 1, repr(message))
		self.TEXT.yview_moveto(1.0)
		
	def sendMsg(self, event = None):
		msg = self.ENTRY.get()
		self.ENTRY.delete(0, len(msg))
		
		if (len(msg) == 0):
			return
			
		self.appendMessage("Me: %s" % (msg))
		MySocket.sendObject(self.conn, ["broadcast", msg])
		
	def createWidgets(self):
		self.CONTROL = PanedWindow(self)
		self.add(self.CONTROL, sticky=W+E)
		
		self.SEND = Button(self)
		self.SEND["text"] = "Send"
		self.SEND["command"] = self.sendMsg
		self.CONTROL.add(self.SEND)

		self.ENTRY = Entry(self)
		self.ENTRY.bind('<Return>', self.sendMsg)
		self.CONTROL.add(self.ENTRY)
		
		self.TEXTGRID = Frame(self)
		self.add(self.TEXTGRID, sticky=W+E+N+S)
		
		self.TEXT = Listbox(self.TEXTGRID)
		self.yscroll = Scrollbar(self.TEXTGRID, orient='vertical', command=self.TEXT.yview)
		self.TEXT["yscrollcommand"] = self.yscroll.set
		self.TEXT.pack(fill = BOTH, expand = 1, side=LEFT)
		self.yscroll.pack(fill = Y, expand = 1)
		
def on_exit():
	if tkMessageBox.askokcancel("Quit", "Are you sure to exit?"):
		root.destroy()

if __name__ == '__main__':
	root = Tk()
	root.title("Chatroom")
	top = ChatRoomClient(root)
	root.protocol('WM_DELETE_WINDOW', on_exit)
	root.mainloop()

